//
//  UserAccountViewModel.swift
//  weibo
//
//  Created by youyongpeng on 15/11/24.
//  Copyright © 2015年 youyongpeng. All rights reserved.
//

import Foundation


class UserAccountViewModel {
    
    // 单利. 解决 access_token 重复从沙盒里获取数据的问题  直接从内存里加载
    static let sharedAccoint = UserAccountViewModel()
    
    // 用户模型
    var account: UserAccoint?
    
    // access_token
    var accessToken: String? {
    
        if !isExpired {
            
            return account?.access_token
        }
        return nil
    }
    
    
    // 判断登录
    var userLogn: Bool {
    
        // access_token 有值, 并且不过期
        return (account?.access_token != nil && !isExpired)
    }
    
    // 路径
    private var accountPath: String {
    
        let path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last!
        
        return (path as NSString).stringByAppendingPathComponent("account.plist")
    }
    
    // 判断日期是否过期
    private var isExpired: Bool {
    
        if account?.expiresData?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
        
            return false
        }
        
        return true
    }
    
    // 构造函数
    private init() {
    
        print(accountPath)
        // 解档
        account = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? UserAccoint
        
        // 判断日期是否过期
        if isExpired {
        
            // 日期过期了, 清空数据
            account = nil
        }
    }
}


// MARK: - 网络加载用户信息
extension UserAccountViewModel {

    func loadUserToken(code: String, finished:(isSuccessde: Bool) -> ()) {
    YYPNetworkTools.sharedTools.loadAccessToken(code) { (result, error) -> () in
    
        if error != nil {
        // 出错了
        print(error)
            
        finished(isSuccessde: false)
    
        return
    }
    
    self.account = UserAccoint(dict: result as! [String: AnyObject])
    
        self.loadUserInfo(self.account!, finished: finished)
    }
        
    }
    
    // 用户信息
    func loadUserInfo(account: UserAccoint, finished:(isSuccessde: Bool) -> ()) {
        
        
        YYPNetworkTools.sharedTools.loadUserInfo(account.uid!) { (result, error) -> () in
            
            if error != nil {
                
                // 出错了
                print(error)
                finished(isSuccessde: false)
            }
            
            guard let dict = result as? [String: AnyObject] else {
                
                // 格式出错了
                finished(isSuccessde: false)
                
                return
            }
            
            account.screen_name = dict["screen_name"] as? String
            account.avatar_large = dict["avatar_large"] as? String
            
            // 成功回调
            finished(isSuccessde: true)
            
            // 保存到归档中
            NSKeyedArchiver.archiveRootObject(account, toFile: self.accountPath)
        }
    }
}